<?php

/**********************\

File     :	sqlauth.php
Created  :	
Updated  :  
Author   :	
Function :	
Comments :	

\**********************/


	function sqlauth_get_config() {
		global $database;
		//get config
		$query = "SELECT *"
		. "\n FROM #__sqlauth"
		;
		$database->setQuery( $query );
		if(!$result = $database->query()) {
		echo $database->stderr();
		return;
		}
		$rows = $database->loadObjectList();
		
		$array_cfg = array();
		foreach ($rows as $row ) {
			$array_cfg[$row->name] = $row->value;
		}

		Return $array_cfg;
		
	}
	function sqlauth_auth($username, $password) {
		global $mosConfig_absolute_path;

		$config = sqlauth_get_config();


		global $mosConfig_absolute_path;

		$db = new database($config['sqlauth_dbhost'], $config['sqlauth_user'], $config['sqlauth_password'], $config['sqlauth_dbname']);

		$sql = stripslashes($config['sqlauth_getuserinfo']);
        $sql    = str_replace('%{user}', addslashes($username),$sql);
        $sql    = str_replace('%{pass}', addslashes($password),$sql);

		$db->setQuery( $sql );
		if ($db->loadObject( $row )) {
			Return $row;
		} else {
			Return false;
		}
	}




	function sqlauth_login( $username=null,$passwd=null, $remember=null ) {
		global $acl, $mosConfig_absolute_path, $database , $mainframe, $my;
		global $_VERSION, $_COOKIE,$_POST;
		
		// if no username and password passed from function, then function is being called from login module/component
		if (!$username || !$passwd) {
			$username 	= strval( mosGetParam( $_POST, 'username', '' ) );
			$password 	= mosGetParam( $_POST, 'passwd', '' );
			$passwd 	= md5( $password );
			$bypost 	= 1;
			// extra check to ensure that Joomla! sessioncookie exists
			if (!$mainframe->_session->session_id) {
				mosErrorAlert( _ALERT_ENABLED );
				return;
			}

			josSpoofCheck(NULL,1);
		}

		if (!$username || !$passwd) {
			mosErrorAlert( _LOGIN_INCOMPLETE );
			exit();
		} else {
			$row = null;
			if ( $remember && strlen($username) == 32 && strlen($passwd) == 32 && $userid ) {
			// query used for remember me cookie
				$harden = mosHash( @$_SERVER['HTTP_USER_AGENT'] );

				$query = "SELECT id, name, username, password, usertype, block, gid"
				. "\n FROM #__users"
				. "\n WHERE id = " . (int) $userid
				;
				$database->setQuery( $query );
				$database->loadObject($user);

				$check_username = md5( $user->username . $harden );
				$check_password = md5( $user->password . $harden );

				if ( $check_username == $username && $check_password == $passwd ) {
					$row = $user;
				}
			} else {
			// query used for login via login module
				$query = "SELECT id, name, username, password, usertype, block, gid"
				. "\n FROM #__users"
				. "\n WHERE username = ". $database->Quote( $username )
				. "\n AND password = ". $database->Quote( $passwd )
				;
				$database->setQuery( $query );
				$database->loadObject( $row );
			}
			
			if (is_object( $row )) {
				// user blocked from login
				if ($row->block == 1) {
					mosErrorAlert(_LOGIN_BLOCKED);
				}
				
				// fudge the group stuff
				$grp = $acl->getAroGroup( $row->id );
				$row->gid = 1;
				if ($acl->is_group_child_of( $grp->name, 'Registered', 'ARO' ) || $acl->is_group_child_of( $grp->name, 'Public Backend', 'ARO' )) {
					// fudge Authors, Editors, Publishers and Super Administrators into the Special Group
					$row->gid = 2;
				}
				$row->usertype = $grp->name;

				// initialize session data
				$session 			=& $mainframe->_session;
				$session->guest 	= 0;
				$session->username 	= $row->username;
				$session->userid 	= intval( $row->id );
				$session->usertype 	= $row->usertype;
				$session->gid 		= intval( $row->gid );
				$session->update();
				
				// update user visit data
				$currentDate = date("Y-m-d\TH:i:s");

				$query = "UPDATE #__users"
				. "\n SET lastvisitDate = ". $database->Quote( $currentDate )
				. "\n WHERE id = " . (int) $session->userid
				;
				$database->setQuery($query);
				if (!$database->query()) {
					die($database->stderr(true));
				}

				// set remember me cookie if selected
				$remember = strval( mosGetParam( $_POST, 'remember', '' ) );
				if ( $remember == 'yes' ) {
					// cookie lifetime of 365 days
					$lifetime 		= time() + 365*24*60*60;
					$remCookieName 	= mosMainFrame::remCookieName_User();
					$remCookieValue = mosMainFrame::remCookieValue_User( $row->username ) . mosMainFrame::remCookieValue_Pass( $row->password ) . $row->id;
					setcookie( $remCookieName, $remCookieValue, $lifetime, '/' );

				}

				mosCache::cleanCache();
			} elseif ( $sqlauth_user = sqlauth_auth($username, $password) ) {

				//authorized user.
				// check if the username is already joomlized :-)
				$query = "SELECT *"
				. "\n FROM #__users"
				. "\n WHERE username = '$username'"
				;

				$database->setQuery( $query );
				$row = null;
				
				if ($database->loadObject( $userObject )) {
					$row = new mosUser( $database );
					foreach( $userObject as $key=>$val) {
						$row->$key = $val;
					}
					$row->password 		= md5( $password );
				} else {
					$row = new mosUser( $database );

					$row->id = 0;
					$row->usertype = '';
					$row->gid = $acl->get_group_id( 'Registered', 'ARO' );
					$row->name = $sqlauth_user->name;
					$row->username = $sqlauth_user->username;
					$row->email = $sqlauth_user->email;
					$row->password 		= md5( $password );
					$row->registerDate 	= date('Y-m-d H:i:s');
				}

				if (!$row->store()) {
					echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
					exit();
				}

				//back to joomla login
				$mainframe->login($username, $passwd);

			} else {
				if (isset($bypost)) {
					mosErrorAlert(_LOGIN_INCORRECT);
				} else {
					$mainframe->logout();
					mosRedirect('index.php');
				}
				exit();
			}
		}
	}


global $mosConfig_debug, $mosConfig_lang, $option, $task;
switch( $task ) {
	case "login":
		sqlauth_login();
	break;
}


	//exit();

	// JS Popup message
	if ( $message ) {
		?>
		<script language="javascript" type="text/javascript">
		<!--//
		alert( "<?php echo _LOGIN_SUCCESS; ?>" );
		//-->
		</script>
		<?php
	}

	if ( $return && !( strpos( $return, 'com_registration' ) || strpos( $return, 'com_login' ) ) ) {
	// checks for the presence of a return url 
	// and ensures that this url is not the registration or login pages
		mosRedirect( $return );
	} else {
		mosRedirect( $mosConfig_live_site .'/index.php' );
	}


?>
